package com.xhsj.user.hr.system.service;

import com.xhsj.user.hr.base.BaseParam;
import com.xhsj.user.hr.process.dto.processDefinition.HandleAuditDto;
import com.xhsj.user.hr.process.hrLeaveProcess.mapper.TbHrApprovalLeaveApplyMapper;
import com.xhsj.user.hr.process.message.service.TbProjectMessageService;
import com.xhsj.user.hr.process.processDefinition.query.ProcessNodeQuery;
import com.xhsj.user.hr.process.processDefinition.service.TbGlobalApprovalTaskService;
import com.xhsj.user.hr.process.query.ApprovalQuery;
import com.xhsj.user.security.entity.LoginUser;
import com.xhsj.user.hr.system.entity.TbGlobalOrganization;
import com.xhsj.user.hr.system.entity.TbGlobalOrganizationApply;
import com.xhsj.user.hr.system.entity.TbHrApprovalDimissionApply;
import com.xhsj.user.hr.system.mapper.TbGlobalOrganizationApplyMapper;
import com.xhsj.user.hr.system.mapper.TbGlobalOrganizationMapper;
import com.xhsj.user.hr.system.mapper.TbGlobalUserMapper;
import com.xhsj.user.hr.system.service.TbGlobalOrganizationApplyService;
import com.xhsj.user.hr.base.BaseService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xhsj.user.hr.system.vo.OrganizationApplyVo;
import com.xhsj.user.utils.Message;
import com.xhsj.user.utils.MessageConstant;
import com.xhsj.user.utils.StringUtils;
import com.xhsj.user.utils.UserUtils;
import org.apache.catalina.User;
import org.springframework.stereotype.Service;

import java.util.*;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.io.Serializable;
import java.util.concurrent.CompletableFuture;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import lombok.extern.slf4j.Slf4j;
/**
 * <p>
 * 组织结构申请记录 服务实现类
 * </p>
 *
 * @author suxiaolin
 * @since Sep 21, 2020 2:05:56 PM
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
//@CacheConfig(cacheNames = "TbGlobalOrganizationApply")
public class TbGlobalOrganizationApplyService extends BaseService<TbGlobalOrganizationApplyMapper, TbGlobalOrganizationApply>{
    @Autowired
    private TbGlobalOrganizationApplyMapper dao;

    @Autowired
    private TbGlobalApprovalTaskService tbGlobalApprovalTaskService;

    @Autowired
    private TbProjectMessageService tbProjectMessageService;

    @Autowired
    private TbGlobalUserMapper tbGlobalUserMapper;

    @Autowired
    private TbGlobalOrganizationService tbGlobalOrganizationService;

    @Autowired
    private TbGlobalOrganizationMapper tbGlobalOrganizationMapper;

    @Autowired
    private TbHrApprovalLeaveApplyMapper tbHrApprovalLeaveApplyMapper;
	/**
	 * 保存
	 * @author suxiaolin
	 * @date Sep 21, 2020 2:05:56 PM
	 */
    @Override
    //@CacheEvict(cacheNames="TbGlobalOrganizationApply", allEntries=true)
    public boolean save(TbGlobalOrganizationApply entity) {
        return super.save(entity);
    }


    /**
     * 保存
     * @author 苏小林
     * @date 2020/9/21 14:12
     * @param: entity
     * @return: boolean
     */
    public boolean savaData(TbGlobalOrganizationApply entity) throws Exception {
        if (StringUtils.isNotBlank(entity.getProcessTaskId()) && StringUtils.isNotBlank(entity.getId())) {
            dao.delDataAndTask(entity.getId(),entity.getProcessTaskId());
            entity.setId(null);
        }

        Integer type = entity.getType();
        int count = tbGlobalOrganizationMapper.getByNameIsRepeat(type,entity.getName());
        if (count > 0) {
            throw new Exception(entity.getName()+":已经存在,请重新输入");
        }

        entity.setDepartmentId(entity.getParentId());
        super.save(entity);
        this.startProcess(entity);
        return true;
    }


    /**
     * 启动流程
     * @author 苏小林
     * @date 2020/9/8 13:46
     * @param: data
     */
    private void startProcess(TbGlobalOrganizationApply entity) throws Exception {
        LoginUser loginAppUser = UserUtils.getLoginAppUser();
        Long userId = loginAppUser.getUserId();
        HandleAuditDto handleAuditDto = new HandleAuditDto(entity.getId(), userId, userId, 1);
        // 流程启动
        ProcessNodeQuery processNodeQuery = tbGlobalApprovalTaskService.startHandleAudit(handleAuditDto, entity.getOrganizationId());
        entity.setBusinessId(handleAuditDto.getBusinessId());
        // 修改申请信息
        this.updateInfoById(entity,processNodeQuery);

        // 发送消息
        ApprovalQuery approvalQuery =
                new ApprovalQuery(handleAuditDto.getDataId(),
                        MessageConstant.MSG_7,
                        processNodeQuery.getUserId(),
                        processNodeQuery.getRoleIds(),
                        4,
                        UserUtils.getLoginAppUser().getUserId(),
                        UserUtils.getLoginAppUser().getFullName());
        this.sendMessage(approvalQuery);
    }

    private void updateInfoById(TbGlobalOrganizationApply entity, ProcessNodeQuery processNodeQuery) {
        entity.setNodeId(processNodeQuery.getNodeId());
        entity.setNodeName(processNodeQuery.getNodeName());
        entity.setUpdateBy(UserUtils.getLoginAppUser().getUserId());
        entity.setUpdateDate(new Date());
        this.updateById(entity);
    }

    public void sendMessage(ApprovalQuery approvalQuery) {
        //保存消息
        CompletableFuture<Void> f = CompletableFuture.runAsync(() -> {
            tbProjectMessageService.sendMessageCommon(approvalQuery);
        });
    }

    /**
	 * 通过id获取数据
	 * @author suxiaolin
	 * @date Sep 21, 2020 2:05:56 PM
	 */
    //@Cacheable(key = "#id",sync = true)
    public TbGlobalOrganizationApply getById(Long id) {
        return dao.getById(id);
    }

	/**
	 * 通过id删除数据
	 * @author suxiaolin
	 * @date Sep 21, 2020 2:05:56 PM
	 */
    @Override
    //@CacheEvict(cacheNames="TbGlobalOrganizationApply", allEntries=true)
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

	/**
	 * 批量删除数据
	 * @author suxiaolin
	 * @date Sep 21, 2020 2:05:56 PM
	 */
    //@CacheEvict(cacheNames="SysDict", allEntries=true)
    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        return super.removeByIds(idList);
    }

	/**
	 * 分页查询数据
	 * @author suxiaolin
	 * @date Sep 21, 2020 2:05:56 PM
	 */
    //@Cacheable(key = "#data",sync = true)
    public IPage<TbGlobalOrganizationApply> selectPage(Map<String,Object> data) {
        int currentPage=1;
        if (!Objects.isNull(data.get("page"))) {
            currentPage=(Integer) data.get("page");
        }
        int pageSize=20;
        if (!Objects.isNull(data.get("size"))) {
            pageSize=(Integer) data.get("size");
        }

        TbGlobalOrganizationApply entity = JSON.parseObject(JSON.toJSONString(data), TbGlobalOrganizationApply.class);
        Page<TbGlobalOrganizationApply> page = new Page(currentPage,pageSize);
        QueryWrapper<TbGlobalOrganizationApply> wrapper = new QueryWrapper(entity);
        return super.selectPage(page, wrapper);
    }

	/**
	 * 查询所有数据
	 * @author suxiaolin
	 * @date Sep 21, 2020 2:05:56 PM
	 */
    @Override
    //@Cacheable(value = "TbGlobalOrganizationApply",sync = true)
    public List<TbGlobalOrganizationApply> selectAll() {
        return super.selectAll();
    }


    /**
     * 查询正在执行任务
     * @author 苏小林
     * @date 2020/9/21 14:38
     * @param: data
     * @return: com.baomidou.mybatisplus.core.metadata.IPage<com.xhsj.user.hr.system.vo.OrganizationApplyVo>
     */
    public IPage<OrganizationApplyVo> findOrganizationApplyRunTask(BaseParam data) {
        Page<TbHrApprovalDimissionApply> page = new Page(data.getPage(),data.getSize());

        Long userId = UserUtils.getLoginAppUser().getUserId();
        List<Long> roleIds = tbGlobalUserMapper.getRoleIdsByUserId(userId);
        return dao.findOrganizationApplyRunTask(page,userId,roleIds);
    }

    /**
     * 查询历史任务
     * @author 苏小林
     * @date 2020/9/21 14:38
     * @param: data
     * @return: com.baomidou.mybatisplus.core.metadata.IPage<com.xhsj.user.hr.system.vo.OrganizationApplyVo>
     */
    public IPage<OrganizationApplyVo> findOrganizationApplyHiTask(BaseParam data) {
        Page<TbHrApprovalDimissionApply> page = new Page(data.getPage(),data.getSize());

        Long userId = UserUtils.getLoginAppUser().getUserId();
        return dao.findOrganizationApplyHiTask(page,userId);
    }

    /**
     * 处理审核
     * @author 苏小林
     * @date 2020/9/21 14:38
     * @param: handleAuditDto
     */
    public void processAudit(HandleAuditDto handleAuditDto) throws Exception {
        ProcessNodeQuery processNodeQuery = tbGlobalApprovalTaskService.handleAudit(handleAuditDto);

        TbGlobalOrganizationApply entity = super.getById(handleAuditDto.getDataId());
        entity.setBusinessId(handleAuditDto.getBusinessId());
        // 修改招聘申请信息
        this.updateInfoById(entity,processNodeQuery);

        if ("完结".equals(processNodeQuery.getNodeName())) {
            TbGlobalOrganization tbGlobalOrganization = new TbGlobalOrganization();
            tbGlobalOrganization.setType(entity.getType());
            tbGlobalOrganization.setName(entity.getName());
            tbGlobalOrganization.setParentId(entity.getDepartmentId());
            tbGlobalOrganization.setDescription(entity.getDescription());
            tbGlobalOrganization.setIsEnable(0);
            tbGlobalOrganizationService.save(tbGlobalOrganization);
        }

        String fullName = tbHrApprovalLeaveApplyMapper.getFullNameByDataId(handleAuditDto.getDataId(),"tb_global_organization_apply");
        // 发送消息
        ApprovalQuery approvalQuery =
                new ApprovalQuery(handleAuditDto.getDataId(),
                        MessageConstant.MSG_7,
                        processNodeQuery.getUserId(),
                        processNodeQuery.getRoleIds(),
                        4,
                        UserUtils.getLoginAppUser().getUserId(),
                        fullName);
        this.sendMessage(approvalQuery);
    }

    /**
     * 查询我的申请
     * @author 苏小林
     * @date 2020/9/21 15:56
     * @param: baseParam
     * @return: com.baomidou.mybatisplus.core.metadata.IPage<com.xhsj.user.hr.system.vo.OrganizationApplyVo>
     */
    public IPage<OrganizationApplyVo> findMyApply(BaseParam data) {
        Page<TbHrApprovalDimissionApply> page = new Page(data.getPage(),data.getSize());

        Long userId = UserUtils.getLoginAppUser().getUserId();
        return dao.findMyApply(page,userId);
    }
}
